package com.moqianfan.mcuassistant.activity;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.moqianfan.mcuassistant.R;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/11/9.
 * 进制计算器
 */

public class CalaulatorActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.RadioChioce)
    RadioGroup RadioChioce;
    @BindView(R.id.NumA)
    Button btnA;
    @BindView(R.id.NumB)
    Button btnB;
    @BindView(R.id.NumC)
    Button btnC;
    @BindView(R.id.NumD)
    Button btnD;
    @BindView(R.id.NumE)
    Button btnE;
    @BindView(R.id.NumF)
    Button btnF;
    @BindView(R.id.ADD)
    Button btnAdd;
    @BindView(R.id.SUBB)
    Button btnSub;
    @BindView(R.id.MUL)
    Button btnMul;
    @BindView(R.id.DIV)
    Button btnDiv;
    @BindView(R.id.Equal)
    Button btnEqual;
    @BindView(R.id.YU)
    Button btnYu;
    @BindView(R.id.Input)
    EditText input;

    private Button[] btnNum = new Button[10];
    private int numId[] = {R.id.Zero, R.id.One, R.id.Two, R.id.Three, R.id.Four, R.id.Five,
            R.id.Six, R.id.Seven, R.id.Eight, R.id.Nine};

    private boolean isClear = false;
    private String result;

    @Override
    public void findViews() {
        setContentView(R.layout.activity_counter);
    }

    public void initViews() {
        for (int i = 0; i < 10; i++) {
            btnNum[i] = (Button) findViewById(numId[i]);
        }
        RadioChioce.setOnCheckedChangeListener(this);
    }

    @Override
    public void initDatas() {

    }

    @OnClick({R.id.Zero, R.id.One, R.id.Two, R.id.Three, R.id.Four, R.id.Five, R.id.Six, R.id.Seven,
            R.id.Eight, R.id.Nine, R.id.image_close, R.id.NumA, R.id.NumB, R.id.NumC, R.id.NumD, R.id.NumE,
            R.id.NumF, R.id.ADD, R.id.SUBB, R.id.MUL, R.id.DIV, R.id.Equal, R.id.Clear, R.id.Delet, R.id.YU})
    public void onClick(View view) {
        Button btn;
        String exp;
        if (view instanceof Button) {
            btn = (Button) view;
            exp = input.getText().toString();
            if (btn.getText().equals("清除")) {
                input.setText("");
            } else if (btn.getText().equals("退格")) {
                if (!TextUtils.isEmpty(input.getText()))
                    input.setText(exp.substring(0, exp.length() - 1));
            } else if (btn.getText().equals("=")) {
                isClear = true;
                if (!TextUtils.isEmpty(input.getText().toString())) {
                    result = String.valueOf(parse(input.getText().toString()));
                    input.append("\n" + result);
                }
            } else {
                if (isClear) {
                    input.setText("");
                    isClear = false;
                }
                input.append(btn.getText());
            }
        }
        switch (view.getId()) {
            case R.id.image_close:
                finish();
                break;
        }
    }

    /**
     * 计算器算法
     *
     * @param content 算数表达式
     * @return 计算结果
     */
    private int parse(String content) {

        if (content.startsWith("+") || content.startsWith("%") || content.startsWith("-")
                || content.startsWith("*") || content.startsWith("/")) {
            input.setText(content.substring(1));
            return parse(content.substring(1));
        }

        // 找到字符串中最后一个左括号
        int startIndex = content.lastIndexOf("(");
        // 如果不是-1,标识这个等式中有括号,继续找与之对应的右括号
        if (startIndex != -1) {
            // 从左括号的位置开始找,找到第一个右括号,这对括号里面一定没有括号,所以就可以交给写好的parse(Stringcontent)方法算出结果！
            int endIndex = content.indexOf(")", startIndex);
            double d = parse(content.substring(startIndex + 1, endIndex));
            return parse(content.substring(0, startIndex) //
                    + d + content.substring(endIndex + 1));
        }

        int index = content.indexOf("+");
        if (index != -1) {
            return parse(content.substring(0, index)) + parse(content.substring(index + 1));
        }
        // 这里<---
        index = content.lastIndexOf("-");
        if (index != -1) {
            return parse(content.substring(0, index)) - parse(content.substring(index + 1));
        }
        // 这里<---
        index = content.indexOf("*");
        if (index != -1) {
            return parse(content.substring(0, index)) * parse(content.substring(index + 1));
        }
        // 这里<---
        index = content.lastIndexOf("/");
        if (index != -1) {
            int num1 = parse(content.substring(0, index));
            int num2 = parse(content.substring(index + 1));
            if (num2 == 0) {
                Toast.makeText(this, "除数不能为0", Toast.LENGTH_SHORT).show();
                input.setText("");
                return 0;
            }
            return num1 / num2;
        }

        index = content.lastIndexOf("%");
        if (index != -1) {
            int num1 = parse(content.substring(0, index));
            int num2 = parse(content.substring(index + 1));
            if (num2 == 0) {
                Toast.makeText(this, "不能和0求余", Toast.LENGTH_SHORT).show();
                input.setText("");
                return 0;
            }
            return num1 % num2;
        }
        return Integer.parseInt(content);
    }

    int currentHex, oldHex = 10;

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        if (input.getText().toString().contains("\n"))
            input.setText(result);
        switch (i) {
            case R.id.Binary:
                currentHex = 2;
                setBtnStatus(2);
                break;
            case R.id.Octal:
                currentHex = 8;
                setBtnStatus(8);
                break;
            case R.id.Decimal:
                currentHex = 10;
                setBtnStatus(10);
                break;
            case R.id.Hex:
                currentHex = 16;
                setBtnStatus(16);
                break;
        }
        isClear = true;
        if (!TextUtils.isEmpty(input.getText().toString())) {
            result = hexChange(oldHex, currentHex).toUpperCase();
            input.append("\n" + result);
        }
        oldHex = currentHex;
    }

    private String hexChange(int oldHex, int currentHex) {
        String returnResult = "";
        String value = input.getText().toString().replace(" ", "");
        switch (oldHex) {
            case 2:
                switch (currentHex) {
                    case 8:
                        returnResult = Integer.toOctalString(Integer.parseInt(value, oldHex));
                        break;
                    case 10:
                        returnResult = Integer.valueOf(value, oldHex).toString();
                        break;
                    case 16:
                        returnResult = Integer.toHexString(Integer.parseInt(value, oldHex));
                        break;
                }
                break;
            case 8:
                switch (currentHex) {
                    case 2:
                        returnResult = Integer.toBinaryString(Integer.valueOf(value, oldHex));
                        break;
                    case 10:
                        returnResult = Integer.valueOf(value, oldHex).toString();
                        break;
                    case 16:
                        returnResult = Integer.toHexString(Integer.valueOf(value, oldHex));
                        break;

                }
                break;
            case 10:
                switch (currentHex) {
                    case 2:
                        returnResult = Integer.toBinaryString(Integer.parseInt(value));
                        break;
                    case 8:
                        returnResult = Integer.toOctalString(Integer.parseInt(value));
                        break;
                    case 16:
                        returnResult = Integer.toHexString(Integer.parseInt(value));
                        break;
                }
                break;
            case 16:
                switch (currentHex) {
                    case 2:
                        returnResult = Integer.toBinaryString(Integer.valueOf(value, oldHex));
                        break;
                    case 8:
                        returnResult = Integer.toOctalString(Integer.valueOf(value, oldHex));
                        break;
                    case 10:
                        returnResult = Integer.valueOf(value, oldHex).toString();
                        break;
                }
                break;


        }
        return returnResult;
    }

    /**
     * 设置按钮可点击状态
     *
     * @param flag 2 -->二进制
     *             8 -->八进制
     *             10-->十进制
     *             16-->十六进制
     */
    private void setBtnStatus(int flag) {
        if (flag == 2) {
            btnNum[0].setEnabled(true);
            btnNum[1].setEnabled(true);
            for (int i = 2; i < 10; i++)
                btnNum[i].setEnabled(false);
            btnA.setEnabled(false);
            btnB.setEnabled(false);
            btnC.setEnabled(false);
            btnD.setEnabled(false);
            btnE.setEnabled(false);
            btnF.setEnabled(false);

            btnAdd.setEnabled(false);
            btnSub.setEnabled(false);
            btnMul.setEnabled(false);
            btnDiv.setEnabled(false);
            btnYu.setEnabled(false);
            btnEqual.setEnabled(false);
        } else if (flag == 8) {
            btnNum[8].setEnabled(false);
            btnNum[9].setEnabled(false);
            for (int i = 0; i < 8; i++)
                btnNum[i].setEnabled(true);
            btnA.setEnabled(false);
            btnB.setEnabled(false);
            btnC.setEnabled(false);
            btnD.setEnabled(false);
            btnE.setEnabled(false);
            btnF.setEnabled(false);

            btnAdd.setEnabled(false);
            btnSub.setEnabled(false);
            btnMul.setEnabled(false);
            btnDiv.setEnabled(false);
            btnYu.setEnabled(false);
            btnEqual.setEnabled(false);
        } else if (flag == 10) {
            for (int i = 0; i < 10; i++)
                btnNum[i].setEnabled(true);
            btnA.setEnabled(false);
            btnB.setEnabled(false);
            btnC.setEnabled(false);
            btnD.setEnabled(false);
            btnE.setEnabled(false);
            btnF.setEnabled(false);

            btnAdd.setEnabled(true);
            btnSub.setEnabled(true);
            btnMul.setEnabled(true);
            btnDiv.setEnabled(true);
            btnYu.setEnabled(true);
            btnEqual.setEnabled(true);
        } else {
            for (int i = 0; i < 10; i++)
                btnNum[i].setEnabled(true);
            btnA.setEnabled(true);
            btnB.setEnabled(true);
            btnC.setEnabled(true);
            btnD.setEnabled(true);
            btnE.setEnabled(true);
            btnF.setEnabled(true);

            btnAdd.setEnabled(false);
            btnSub.setEnabled(false);
            btnMul.setEnabled(false);
            btnDiv.setEnabled(false);
            btnYu.setEnabled(false);
            btnEqual.setEnabled(false);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(R.anim.push_right_in,
                    R.anim.push_right_out);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }
}
